#include "qtcpfilerecieve.h"
#include "ui_qtcpfilerecieve.h"

QTcpFileRecieve::QTcpFileRecieve(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QTcpFileRecieve)
{
    ui->setupUi(this);
    qTcpSocket = new QTcpSocket(this);
    ui->textEditShow->setReadOnly(true);
}

QTcpFileRecieve::~QTcpFileRecieve()
{
    delete ui;
}

void QTcpFileRecieve::on_connectButton_clicked()
{
    QString ip = ui->lineEditIp->text();
    qint16 port = ui->lineEditPort->text().toInt();
    qDebug()<<ip<<":"<<port;

    if (qTcpSocket->isOpen()) {
        QString showText = QString(ip).append(":%1").arg(port);
        ui->textEditShow->append(QString("已连接到服务器：%1了,请先断开连接,再重新链接").arg(showText));
        return;
    }
    qTcpSocket->connectToHost(QHostAddress(ip),port);
    connect(qTcpSocket,&QTcpSocket::connected,
            [=](){
        //文本区域展示链接状态
        QString showText = QString(ip).append(":%1").arg(port);
        qDebug()<<showText;
        if (qTcpSocket->isOpen()) {
            ui->textEditShow->append(QString("已连接到服务器：%1").arg(showText));
        }else {
            ui->textEditShow->append(QString("连接到服务器：%1 未响应！").arg(showText));
        }
    });
    connect(qTcpSocket,&QTcpSocket::readyRead,
            [=](){
        QByteArray readBuf = qTcpSocket->readAll();

        QString recieveHead = QString::fromUtf8(readBuf);
        QString packageHead =  recieveHead.section("###",0,0);
        //当前包是头部包结构
        if (packageHead==QString("HEAD")) {
            recieveSize=0;
            qDebug()<<recieveHead;
            QString fileName =  recieveHead.section("###",1,1);
            fileSize =  recieveHead.section("###",2,2).toLongLong();
            ui->progressBar->setMaximum(fileSize);
            ui->progressBar->setMinimum(0);
            qDebug()<<"文件名称:"<<fileName <<"文件大小:"<<fileSize;
            saveFileName =  ui->lineEditDownloadPath->text();

            if (saveFileName.isEmpty()) {
                saveFileName = "../tmp";
            }
            ui->textEditShow->append(
                        QString("接收到服务端文件,保存路径:%1")
                        .arg(saveFileName)
                        );
            qFile.setFileName(saveFileName);
            isOpenSuccess = qFile.open(QIODevice::WriteOnly);
            if (isOpenSuccess) {

                qint64 writeSize = qFile.write(readBuf.remove(0,300));
                recieveSize+=writeSize;
                ui->progressBar->setValue(recieveSize);
            }
        }
        //当前包是数据包结构
        else{
            if (isOpenSuccess) {
                qint64 writeSize = qFile.write(readBuf);
                recieveSize+=writeSize;
                ui->progressBar->setValue(recieveSize);
                if (recieveSize>=fileSize) {
                    QFileInfo qFileInfo(saveFileName);
                    if (recieveSize==fileSize) {
                        ui->textEditShow->append(
                                    QString("接收到服务端文件%1大小%2,传输完成!")
                                    .arg(qFileInfo.absoluteFilePath())
                                    .arg(recieveSize)
                                    );
                        isOpenSuccess = false;
                    }else {
                        ui->textEditShow->append(
                                    QString("接收到服务端文件%1%2,发生未知错误!")
                                    .arg(qFileInfo.absoluteFilePath())
                                    .arg(recieveSize)
                                    );
                    }
                    qFile.close();
                }

            }else {
                qDebug()<<"打开文件"<<saveFileName<<"失败!或者文件流已关闭";
            }
        }
    });

}

void QTcpFileRecieve::on_downloadButton_clicked()
{

}

void QTcpFileRecieve::on_SelectDownloadPath_clicked()
{
    QString savePath = QFileDialog::getSaveFileName(
                this,"保存路径","../","*.*");
    ui->lineEditDownloadPath->setText(savePath);
}

void QTcpFileRecieve::on_disconnectButton_clicked()
{
    qTcpSocket->close();
     ui->textEditShow->append("已断开连接");
}
